<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>默认首页</title>
    <style>
        div {
            margin: 20px;
        }

        #preview img {
            margin: 5px;
        }
    </style>
</head>
<body>
Welcome to winshu-spring-star

<div class="choose-box">
    <h3>上传文件示例</h3>
    <input type="file" id="file" name="file" multiple="multiple"/>
    <button id="upload">上传</button>
</div>
<div id="preview">
</div>
<script>
    document.getElementById("upload").onclick = function () {
        let file = document.getElementById("file");
        console.log(file.files.length);

        let formData = new FormData();
        for (let i = 0; i < file.files.length; i++) {
            formData.append("file", file.files[i]);
        }

        let xhttp = new XMLHttpRequest();
        xhttp.onreadystatechange = function () {
            if (this.readyState === 4 && this.status === 200) {
                console.log(this.responseText);

                let data = JSON.parse(this.responseText);
                if (Array.isArray(data)) {
                    let preview = document.getElementById("preview");
                    preview.innerHTML = "";

                    for (let i = 0; i < data.length; i++) {
                        let node = document.createElement("img");
                        node.src = getImageUrl(data[i].contextPath, data[i].fullName);
                        node.title = data[i].fileSize + "KB";
                        node.style.width = "100px";
                        node.style.height = "100px";

                        preview.appendChild(node);
                    }
                }
            }
        };
        xhttp.open("POST", "upload2", true);
        xhttp.setRequestHeader("Token", "Hello");
        xhttp.send(formData);
    };

    function getImageUrl(context, fullName) {
        let url = document.location.toString();
        let arrUrl = url.split("//");

        let start = arrUrl[1].indexOf("/");
        let relUrl = arrUrl[1].substring(start);//stop省略，截取从start开始到结尾的所有字符

        if (relUrl.indexOf("?") !== -1) {
            relUrl = relUrl.split("?")[0];
        }
        return document.location.origin + relUrl + "attachment/" + fullName + "?context=" + context;
    }
</script>
</body>
</html>